layui.config({
    base: "static/layui/module/"
}).extend({
    dynamicCondition: 'dynamicCondition/dynamicCondition'
}).use(['form','layer','jquery','table','laydate','upload','element','dynamicCondition'],function(){
    var form = layui.form,
        layer = layui.layer,
        laypage = layui.laypage,
        $ = layui.jquery,
        table=layui.table,
        upload = layui.upload,
        laydate =layui.laydate,
        element = layui.element,
        dynamicCondition=layui.dynamicCondition;
    var tableData;
    var tableIns = table.render({
        elem:'#table'
        ,title:'用户列表'
        ,url:'/user/list'
        ,method:'post'
        ,page: true //开启分页
        ,limit: 10
        ,limits: [10,15,18,20,30,40,50]
        ,loading: true
        ,cols: [[ //表头
            {type:'numbers', title:'序号'}
            ,{type:'checkbox'}
            ,{field: 'userCode', title: '用户账号', sort:true}
            ,{field: 'userName', title: '用户名称', sort:true}
            ,{field: 'userPhone', title: '电话', sort:true}
//    		,{field: 'userAge', title: '年龄', sort:true}
//    		,{field: 'userSex', title: '性别', sort:true}
            ,{field: 'userAddr', title: '地址', sort:true}
            ,{field: 'userEmail', title: '邮箱', sort:true}
   		    ,{field: 'departmentName', title: '部门', sort:true}
            ,{field: 'roleName', title: '角色', sort:true}
            ,{field: 'pdRoleName', title: '审批角色', sort:true}
        ]]
        ,text: {
            none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
        }
        ,toolbar:'#tableToolbar'
        ,defaultToolbar: ['filter']
        ,done: function(res, curr, count){
            tableData = res.data;
        }
    });

    var dataFields = [
        {field:"user_code", title:"用户编码", edit:"text"}
        ,{field:"user_name", title:"名称", edit:"text"}
        //,{field:"user_sex", title:"性别", edit:"text"}
        ,{field:"create_time", title:"创建日期", edit:"date"}
  	 	,{field:"dept-department_id", title:"部门",ops:"equal", edit:"select",templet:"#department"}
        ,{field:"role-role_id", title:"角色", ops:"equal", edit:"select", templet:"#role"}
    ];

    var dc = dynamicCondition.create({
        fields:dataFields
        ,tableId:"table"
        ,conditionTextId:"#findMsg"
        ,type:"complex"
        ,requestDataType:"json"
        ,counts:2
        ,queryCallBack:function(requestData){
        }
    });

    table.on('toolbar(table)', function(obj){
        var tableCheckData = table.checkStatus(obj.config.id).data;
        switch(obj.event){
            case 'find':
                dc.open();
                break;
            case 'pdRole':
                if(tableCheckData.length != 1){
                    top.layer.msg("请选择单个数据");
                    return;
                }
                var index = layer.open({
                    type: 2
                    ,title: '设置用户审批角色'
                    ,area: ['100%', '80%']
                    ,content: '/user/pdRoleHtml?id='+tableCheckData[0].id
                    ,btn: ['保存', '取消']
                    ,yes: function(index, layero){
                        var body = layui.layer.getChildFrame('body', index);
                        var pdRole = body.find("input[name='pdRole']:checked");
                        var pdRoleIds = new Array();
                        $.each(pdRole, function(index, e){
                            pdRoleIds.push(e.value);
                        })
                        var user_data = new Object();
                        user_data.userId = tableCheckData[0].id;
                        user_data.roleIds = pdRoleIds.join();

                        var shadeIndex = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.4});
                        $.post("/user/pdRoleSet",user_data,function(data){
                            if(data){
                                top.layer.msg("设置成功");
                                table.reload('table');
                            }else{
                                top.layer.msg("设置失败");
                            }
                            top.layer.close(shadeIndex);
                            layer.close(index);
                        },"json")
                    }
                });
                break;
            case 'add':
                var index = layer.open({
                    type: 2
                    ,title: "新增用户"
                    ,maxmin: true
                    ,area: ['50%', '100%']
                    ,content: '/user/addHtml'
                    ,offset: 'r'
                    ,btn: ['保存','返回']
                    ,yes: function(index, layero){
                        var body = layer.getChildFrame('body', index);
                        var userCode = body.find("#userCode").val();
                        var userName = body.find("#userName").val();
                        var userPhone = body.find("#userPhone").val();
                        //var userAge = body.find("#userAge").val();
                        //var userSex = body.find("#userSex").val();
                        var userAddr = body.find("#userAddr").val();
                        var userEmail = body.find("#userEmail").val();
		        		var departmentId = body.find("#deptId").val();
                        var roleId = body.find("#roleId").val();
                        var roleName = body.find("#roleName").val();

                        if(userCode == ''){
                            top.layer.msg("请填写用户编号");
                            return;
                        }
                        if(userName == ''){
                            top.layer.msg("请填写用户名称");
                            return;
                        }
//		        		if(userPhone == ''){
//		        			top.layer.msg("请填写电话");
//		        			return;
//		        		}
//		        		if(userSex == ''){
//		        			top.layer.msg("请填写性别");
//		        			return;
//		        		}
//		        		if(userEmail == ''){
//		        			top.layer.msg("请填写邮箱");
//		        			return;
//		        		}
		        		if(departmentId == ''){
		        			top.layer.msg("请选择部门");
		        			return;
		        		}
                        if(roleId == ''){
                            top.layer.msg("请选择角色");
                            return;
                        }

                        var userData = {
                            userCode:userCode
                            ,userName:userName
                            ,userPhone:userPhone
                            //,userAge:userAge
                            //,userSex:userSex
                            ,userAddr:userAddr
                            ,userEmail:userEmail
		        			,departmentId:departmentId
                            ,roleId:roleId
                        }

                        var shadeIndex = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.4});
                        $.ajax({
                            url: "/user/add",
                            type: "post",
                            data: userData,
                            success: function (d) {
                                if(d.code == '200'){
                                    top.layer.msg("新增成功",{icon:1});
                                    layer.close(index);
                                }else{
                                    top.layer.msg("新增失败，"+d.msg,{icon:2});
                                }
                                top.layer.close(shadeIndex);
                                table.reload('table');
                            },
                            error: function () {
                                top.layer.close(shadeIndex);
                                alert("新增失败！");
                            }
                        })
                    }
                });
                break;
            case 'upd':
                if(tableCheckData.length != 1){
                    top.layer.msg("请选择单个数据");
                    return;
                }
                var index = layer.open({
                    type: 2
                    ,title: "修改"
                    ,maxmin: true
                    ,area: ['50%', '100%']
                    ,content: '/user/updateHtml?id='+tableCheckData[0].id
                    ,offset: 'r'
                    ,btn: ['保存','返回']
                    ,yes: function(index, layero){
                        var body = layer.getChildFrame('body', index);

                        var userCode = body.find("#userCode").val();
                        var userName = body.find("#userName").val();
                        var userPhone = body.find("#userPhone").val();
                        //var userAge = body.find("#userAge").val();
                        //var userSex = body.find("#userSex").val();
                        var userAddr = body.find("#userAddr").val();
                        var userEmail = body.find("#userEmail").val();
		        		var departmentId = body.find("#deptId").val();
                        var roleId = body.find("#roleId").val();
                        var roleName = body.find("#roleName").val();

                        if(userCode == ''){
                            top.layer.msg("请填写用户编号");
                            return;
                        }
                        if(userName == ''){
                            top.layer.msg("请填写用户名称");
                            return;
                        }
//		        		if(userPhone == ''){
//		        			top.layer.msg("请填写电话");
//		        			return;
//		        		}
//		        		if(userSex == ''){
//		        			top.layer.msg("请填写性别");
//		        			return;
//		        		}
//		        		if(userEmail == ''){
//		        			top.layer.msg("请填写邮箱");
//		        			return;
//		        		}
		        		if(departmentId == ''){
		        			top.layer.msg("请选择部门");
		        			return;
		        		}
                        if(roleId == ''){
                            top.layer.msg("请选择角色");
                            return;
                        }

                        var userData = {
                            id:tableCheckData[0].id
                            ,userCode:userCode
                            ,userName:userName
                            ,userPhone:userPhone
                            //,userAge:userAge
                            //,userSex:userSex
                            ,userAddr:userAddr
                            ,userEmail:userEmail
		        			,departmentId:departmentId
                            ,roleId:roleId
                        }
                        console.log(userData);
                        var shadeIndex = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.4});
                        $.ajax({
                            url: "/user/update",
                            type: "post",
                            data: userData,
                            success: function (d) {
                                if(d.code == '200'){
                                    top.layer.msg("修改成功",{icon:1});
                                    layer.close(index);
                                }else{
                                    top.layer.msg("修改失败，"+d.msg,{icon:2});
                                }
                                top.layer.close(shadeIndex);
                                table.reload('table');
                            },
                            error: function () {
                                top.layer.close(shadeIndex);
                                alert("修改失败！");
                            }
                        })
                    }
                });
                break;
            case 'del':
                if(tableCheckData.length == 0){
                    layer.msg("请选择数据");
                    return;
                }
                top.layer.confirm('是否删除?', {icon: 3, title:'提示'}, function(index){
                    var userCodes = new Array();
                    $.each(tableCheckData,function(index, e){
                        userCodes.push(e.id);
                    });
                    var shadeIndex = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.4});
                    $.ajax({
                        url: "/user/delete",
                        type: "post",
                        data: JSON.stringify(userCodes),
                        contentType:"application/json",
                        success: function (d){
                            if(d.code == '200'){
                                top.layer.msg("删除成功",{icon:1});
                            }else{
                                top.layer.msg("删除失败",{icon:2});
                            }
                            top.layer.close(shadeIndex);
                            table.reload('table');
                        },
                        error: function(){
                            top.layer.close(shadeIndex);
                            alert("删除失败！");
                        }
                    });
                    top.layer.close(index);
                });
                break;
            case 'reset':
                if(tableCheckData.length != 1){
                    top.layer.msg("请选择单个数据");
                    return;
                }
                var shadeIndex = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.4});
                $.post('/user/pwd_reset',{id:tableCheckData[0].id},function(d){
                    if(d.code == '200'){
                        top.layer.alert("密码重置成功！重置后的密码为：123456",{icon:1});
                        layer.close(index);
                    }else{
                        top.layer.msg("密码重置失败，"+d.msg,{icon:2});
                    }
                    top.layer.close(shadeIndex);
                    table.reload('table');
                });
                break;
        };
    });
})
